package hz.mobileproject.pda.ui.activity.work;

import android.content.Intent;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.activity.CaptureActivity;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.text.SimpleDateFormat;
import java.util.List;

import hz.mobileproject.pda.R;
import hz.mobileproject.pda.app.MainApp;
import hz.mobileproject.pda.broadcast.HandleBroadcast;
import hz.mobileproject.pda.broadcast.IShowBarcodeStr;
import hz.mobileproject.pda.entity.AdmonishLeiXingBean;
import hz.mobileproject.pda.entity.request.Request_Adminish_Add;
import hz.mobileproject.pda.entity.request.Request_loadPersioneInfo;
import hz.mobileproject.pda.entity.request.Request_loadPoliceInfo;
import hz.mobileproject.pda.entity.response.Response_loadPoliceInfo;
import hz.mobileproject.pda.entity.response.Rp_loadPrisonerInfo;
import hz.mobileproject.pda.listener.CustomNetCallBack;
import hz.mobileproject.pda.network.Constance;
import hz.mobileproject.pda.ui.adapter.AdmonishPopAdapter;
import hz.mobileproject.pda.ui.base.BaseActivity;
import hz.mobileproject.pda.ui.view.CustomPopWindow;
import hz.mobileproject.pda.ui.view.LoadingDialog;
import hz.mobileproject.pda.utils.CommonUtil;
import hz.mobileproject.pda.utils.HttpRqUtils;

/**
 * 训诫界面
 */
@ContentView(R.layout.activity_admonish)
public class AdmonishActivity extends BaseActivity implements IShowBarcodeStr {

    private static final int REQUEST_CODE_POLICE = 0x1001;
    private static final int REQUEST_CODE_PRISONER = 0x1002;
    /**
     * 扫码相关---------------------------
     */
    private HandleBroadcast mHandleBroadcast;
    private SoundPool mSoundpool;
    private LoadingDialog mLoadingDialog;
    //红外扫描音效id
    private int mSoundid;
    //扫描成功返回码
    private static final int SCAN_RESULT_OK = 0xA1;
    private Gson mGson;
    //当前扫码民警
    private Response_loadPoliceInfo mPolice;
    //当前扫码罪犯
    private Rp_loadPrisonerInfo mPrisoner;

    private List<AdmonishLeiXingBean> admonishLeiXingBeanList;
    private String mSelectLeiXing;
    private String mSelectId;

    @ViewInject(R.id.tv_policeName)
    private TextView tv_policeName;
    @ViewInject(R.id.tv_prisonerName)
    private TextView tv_prisonerName;
    @ViewInject(R.id.tv_policeID)
    private TextView tv_policeID;
    @ViewInject(R.id.tv_prisonerID)
    private TextView tv_prisonerID;
    @ViewInject(R.id.tv_policeDept)
    private TextView tv_policeDept;
    @ViewInject(R.id.tv_prisonerDept)
    private TextView tv_prisonerDept;
    @ViewInject(R.id.tv_tanhua_leixing)
    private TextView tv_tanhua_leixing;
    @ViewInject(R.id.et_reson_admonish)
    private EditText et_reson_admonish;   //训诫原因
    private String metReson;


    @Override
    protected void initData() {
        mGson = new Gson();
        mLoadingDialog = new LoadingDialog(this);
        //打开红外扫码  扫描民警
        openScan(REQUEST_CODE_POLICE);


        //加载类型请求接口（无请求参数）
        HttpRqUtils.httpGet(Constance.BASE_URL + Constance.URL_ADMONITION_LOADTYPE, loadTypeCallBack);

    }

    private CustomNetCallBack loadTypeCallBack = new CustomNetCallBack() {
        @Override
        public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
            admonishLeiXingBeanList = mGson.fromJson(data,new TypeToken<List<AdmonishLeiXingBean>>(){}.getType());
        }

        @Override
        public void onErrorFromSer(int rtnCode, String rtnMsg) {

        }

        @Override
        public void onErrorFromNet(Throwable ex, boolean isOnCallback) {

        }
    };

    @Event({R.id.tv_policeName, R.id.tv_prisonerName, R.id.tv_tanhua_leixing,R.id.bt_submit_admonish})
    private void click(View v) {
        switch (v.getId()) {
            case R.id.tv_police_name:
                openScan(REQUEST_CODE_POLICE);
                break;
            case R.id.tv_prisonerName:
                openScan(REQUEST_CODE_PRISONER);
                break;
            case R.id.tv_tanhua_leixing:   //点击训诫类型
                showPopWindow(admonishLeiXingBeanList, tv_tanhua_leixing);
                break;
            case R.id.bt_submit_admonish:
                //请求接口保存
                if(TextUtils.isEmpty(mSelectId)) {
                    ToastUtils.showLong("请选择训诫类型");
                    return;
                }
                metReson = et_reson_admonish.getText().toString().trim();
                if(TextUtils.isEmpty(metReson)) {
                    ToastUtils.showLong("请输入训诫原因");
                    return;
                }
                Request_Adminish_Add add = new Request_Adminish_Add();
                add.setCus_number(mPolice.getCus_number() + "");
                add.setDept_id(mPolice.getDepartment_id() + "");
                add.setDept_name(mPolice.getDepartment_name());
                add.setPolice_id(mPolice.getPolice_id());
                add.setPolice_name(mPolice.getPolice_name());
                add.setPrisoner_id(mPrisoner.getPrisoner_id());
                add.setPrisoner_name(mPrisoner.getPrisoner_name());
                add.setType(mSelectId);   //类型
                add.setRemark(metReson);
                add.setTime(TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));
                //加载训诫保存接口
                HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_ADMONITION_ADD,add,admonishAddCallBack);
                break;
        }
    }

    private CustomNetCallBack admonishAddCallBack = new CustomNetCallBack() {
        @Override
        public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
            mSelectId = null;
            metReson = null;
            ToastUtils.showLong("训诫上传成功");
            finish();
//            tv_tanhua_leixing.setText("请选择训诫类型");
//            tv_tanhua_leixing.setTextColor(Color.parseColor("#4084E4"));
//            tv_tanhua_leixing.setTextSize(16);
//            et_reson_admonish.setText("");
        }

        @Override
        public void onErrorFromSer(int rtnCode, String rtnMsg) {

        }

        @Override
        public void onErrorFromNet(Throwable ex, boolean isOnCallback) {

        }
    };


    private void showPopWindow(final List<AdmonishLeiXingBean> eduTypes, final View showAsDropDownView) {
        if (eduTypes == null || eduTypes.size() <= 0) {
            return;
        }
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_custom_list, null);
        //处理popWindow 显示内容
        ListView listView = (ListView) contentView.findViewById(R.id.lv_dialog);
        AdmonishPopAdapter adapter = new AdmonishPopAdapter(this, eduTypes);
        listView.setAdapter(adapter);
        //创建并显示popWindow
        final CustomPopWindow mListPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .size(showAsDropDownView.getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT)//显示大小
                .create()
                .showAsDropDown(showAsDropDownView, 0, 0);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mListPopWindow.dissmiss();
                ((TextView) showAsDropDownView).setText(eduTypes.get(position).value);
                switch (showAsDropDownView.getId()) {
                    case R.id.tv_tanhua_leixing://点击训诫类型
                        mSelectLeiXing = eduTypes.get(position).value;
                        mSelectId = eduTypes.get(position).key;
                        break;

                }
            }
        });
    }



    /**
     * 请求网络接口获取民警信息
     *
     * @param scanStr
     */
    private void getPliceInfoFromSer(String scanStr) {
//        if (scanStr.indexOf("P") != 0) {
//            ToastUtils.showLong("条码格式错误，请确认为民警条码");
//            return;
//        }
//        scanStr = scanStr.substring(scanStr.indexOf("P") + 1);
        scanStr = scanStr.contains("P") ? scanStr.substring(1): scanStr;
        Request_loadPoliceInfo rq_lpi = new Request_loadPoliceInfo();
        rq_lpi.setCusNumber(SPUtils.getInstance("app_login").getString(Constance.SP_CUSNUMBER));
        rq_lpi.setPoliceCode(scanStr);
        //发送获取民警信息接口请求
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_LOAD_POLICE_INFO, rq_lpi, policeInfoCallback);
    }

    /**
     * 获取民警信息接口回调
     */
    private CustomNetCallBack policeInfoCallback = new CustomNetCallBack() {
        @Override
        public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
            LogUtils.e(data);
            Response_loadPoliceInfo loadPoliceInfo = mGson.fromJson(data, Response_loadPoliceInfo.class);
            if (loadPoliceInfo == null) {
                ToastUtils.showLong("民警信息为空");
                return;
            }
            tv_policeName.setText(loadPoliceInfo.getPolice_name());
            tv_policeID.setText(loadPoliceInfo.getPolice_code());
            tv_policeDept.setText(loadPoliceInfo.getDepartment_name());
            mPolice = loadPoliceInfo;

            //打开扫描罪犯
            mLoadingDialog.dismiss();
            openScan(REQUEST_CODE_PRISONER);

        }

        @Override
        public void onErrorFromSer(int rtnCode, String rtnMsg) {
            ToastUtils.showLong("获取民警信息失败");
        }

        @Override
        public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
            ToastUtils.showLong("获取民警信息失败");
            LogUtils.e(ex);
        }
    };

    /**
     * 请求网络接口获取罪犯信息
     *
     * @param scanStr
     */
    private void getPrisonerInfoFromSer(String scanStr) {
        scanStr = scanStr.substring(scanStr.indexOf("P") + 1);
        LogUtils.e(scanStr);
        Request_loadPersioneInfo rq_lpi = new Request_loadPersioneInfo();
        rq_lpi.setCusNumber(MainApp.getInstance().getLoginUser().getCus_number()+"");
        rq_lpi.setPrisonerId(scanStr);
        //发送获取罪犯信息接口请求
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_LOAD_PRISONER_INFO, rq_lpi, prisonerInfoCallback);
    }

    /**
     * 获取罪犯信息接口回调
     */
    private CustomNetCallBack prisonerInfoCallback = new CustomNetCallBack() {
        @Override
        public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
            LogUtils.e(data);
            Rp_loadPrisonerInfo loadPrisonerInfo = mGson.fromJson(data, Rp_loadPrisonerInfo.class);
            if (loadPrisonerInfo == null) {
                ToastUtils.showLong("罪犯信息为空");
                return;
            }
            tv_prisonerName.setText(loadPrisonerInfo.getPrisoner_name());
            tv_prisonerID.setText(loadPrisonerInfo.getPrisoner_id());
            tv_prisonerDept.setText(loadPrisonerInfo.getDepartment_name());
            mPrisoner = loadPrisonerInfo;

            mLoadingDialog.dismiss();
        }

        @Override
        public void onErrorFromSer(int rtnCode, String rtnMsg) {
            ToastUtils.showLong("获取罪犯信息失败");
        }

        @Override
        public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
            ToastUtils.showLong("获取罪犯信息失败");
            LogUtils.e(ex);
        }
    };


    /**
     * 打开扫描
     */
    private void openScan(int requestCode) {
        if (Constance.isNeiMeng) {  //如果是演示版本则打开相机扫描
            //打开二维码扫描界面
            if (CommonUtil.isCameraCanUse()) {
                Intent intent = new Intent(this, CaptureActivity.class);
                startActivityForResult(intent, requestCode);
            } else {
                Toast.makeText(this, "请打开此应用的摄像头权限！", Toast.LENGTH_SHORT).show();
            }
        } else {
            mHandleBroadcast = new HandleBroadcast(this, this);
            mSoundpool = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 100); // MODE_RINGTONE
            mSoundid = mSoundpool.load("/etc/Scan_new.ogg", 1);
            if (requestCode == REQUEST_CODE_POLICE) {
                mLoadingDialog.setTag(REQUEST_CODE_POLICE);
                mLoadingDialog.setMessage("请扫描民警二维码").show();
            } else if (requestCode == REQUEST_CODE_PRISONER) {
                mLoadingDialog.setTag(REQUEST_CODE_PRISONER);
                mLoadingDialog.setMessage("请扫描罪犯二维码").show();
            }
        }
    }


    /**
     * 摄像头扫码回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != SCAN_RESULT_OK) {
            return;
        }
        //扫描结果回调
        Bundle bundle = data.getExtras();
        String scanStr = bundle.getString("qr_scan_result");
        if (requestCode == REQUEST_CODE_POLICE) {
            //获取民警信息
            getPliceInfoFromSer(scanStr);
        } else if (requestCode == REQUEST_CODE_PRISONER) {
            //获取罪犯信息
            getPrisonerInfoFromSer(scanStr);
        }
    }





    @Override
    public void updateText(String msg) {
        if (!mLoadingDialog.isShowing()) {
            return;
        }
        mSoundpool.play(mSoundid, 1, 1, 0, 0, 1);
        if (mLoadingDialog.getTag() == REQUEST_CODE_POLICE) {
            //获取民警信息
            getPliceInfoFromSer(msg);
        } else if (mLoadingDialog.getTag() == REQUEST_CODE_PRISONER) {
            //获取罪犯信息
            getPrisonerInfoFromSer(msg);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            if(mHandleBroadcast != null) {
                mHandleBroadcast.overBroadcastReceiver(this);
            }
        }catch (Exception e) {

        }
    }
}
